package com.my.hadoop;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;

import java.io.IOException;
import java.net.URI;
import java.util.Date;

public class HdfsFileStatus {

    private static final Configuration conf;

    static {
        conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://hadoop102:8020");
        System.out.println("conf初始化完成");
    }

    public static void main(String[] args) {
        show("/file/book/");
    }

    private static void show(String dirPath) {
        FileSystem fileSystem = null;
        try {
            fileSystem = FileSystem.get(new URI("hdfs://hadoop102:8020"), conf, "root");
            Path path = new Path(dirPath);
            RemoteIterator<FileStatus> iterator = fileSystem.listStatusIterator(path);
            while (iterator.hasNext()){
                FileStatus fs = iterator.next();
                Path thisPath = fs.getPath();
                String fileName = thisPath.getName();
                long mbSize = fileSystem.getContentSummary(thisPath).getLength() / 1024 / 1024;
                Date lastUpdateTime = new Date(fs.getModificationTime());
                System.out.println(fileName+":"+mbSize+":"+lastUpdateTime);
            }
        } catch (Exception e) {
            System.out.println("遍历文件夹出现异常：" + e.getMessage());
        } finally {
            try {
                if (fileSystem != null) fileSystem.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
